package ca.on.eho.qa.applogic1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import ca.on.eho.qa.model.User;
import ca.on.eho.qa.applogic.UserHelper;
import ca.on.eho.qa.applogic1.ApplicationManager1;
import ca.on.eho.qa.applogic1.DriverBasedHelper;

import ca.on.eho.qa.pages.Page;
import ca.on.eho.qa.pages.PageManager;
import ca.on.eho.qa.pages.AnyInternalPage;
import ca.on.eho.qa.pages.LoginPage;

public class UserHelper1 extends DriverBasedHelper implements UserHelper {

	private ApplicationManager1 manager;

	public UserHelper1(ApplicationManager1 manager) {
		super(manager.getWebDriver());
		this.manager = manager;
	}

	@Override
	public void loginAs(User user) {
		pages.loginPage.ensurePageLoaded();
		pages.loginPage.setUserIdField(user.getId());
		pages.loginPage.setPasswordField(user.getPassword());
		pages.loginPage.clickLoginButton();
	}

	@Override
	public void logout() {	
		pages.anyInternalPage.ensurePageLoaded();
		pages.anyInternalPage.clickLogoutLink();
	}

	@Override
	public boolean isLoggedIn() {		
		return pages.anyInternalPage.waitPageLoaded();
	}
	
	@Override
	public boolean isLoggedInAs(User user) {		
		return isLoggedIn(); 
		// Label displays First + Last name. We do not know user names.
		// &&  user.getFirstLastName().equals(driver.findElement(AnyInternalPage.by_userNameLabel).getText());
	}

	@Override
	public boolean isNotLoggedIn() {
		return pages.loginPage.waitPageLoaded();
	}


	public void loginIfNecessary(User user, String baseUrl) throws Exception {

		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

		if (!isElementPresent(AnyInternalPage.by_homeImage)) {

			if (isElementPresent(LoginPage.by_loginHeader)) {
				loginAs(user);
			} else {
				driver.get(baseUrl);
				loginAs(user);
			}
		}
	}

}
